<script setup lang="ts" name="home">
import type { ListAndQuestionCategoryVO, QuestionCategoriesListVO } from './data'
import { useRoute } from 'vue-router'
import { getCategories } from './service'
import { computed, onMounted, ref } from 'vue'
import Categories from './components/Categories.vue'
import Topics from './components/Topics.vue'

const route = useRoute()

const categories = ref<ListAndQuestionCategoryVO[]>([])

onMounted(() =>
  getCategories().then((data) => (categories.value = data.sort((a, b) => Number(b.sort) - Number(a.sort))))
)

const shownCategoryId = computed<string>(() => (route.query.category as string) ?? categories.value[0]?.id)

const topics = computed<QuestionCategoriesListVO[]>(
  () => categories.value.find((item) => item.id === shownCategoryId.value)?.questionCategorieList ?? []
)

const cacheSize = (el: Element) => {
  const { width, height } = el.getBoundingClientRect()
  Object.assign((el as HTMLElement).style, {
    width: `${width}px`,
    height: `${height}px`,
  })
}
</script>

<template>
  <div class="mx-auto! max-w-11/12 w-360 flex flex-col gap-7 pt-7! px-5!">
    <h1 class="text-2xl/none font-normal">面试题库</h1>
    <Categories :items="categories" :shown-category-id="shownCategoryId" />
    <div class="relative">
      <Transition
        enter-from-class="opacity-0"
        enter-active-class="transition duration-300"
        leave-active-class="transition duration-300 absolute!"
        leave-to-class="opacity-0"
        @before-leave="cacheSize"
      >
        <Topics :key="shownCategoryId" :items="topics" />
      </Transition>
    </div>
  </div>
</template>
